package com.cmdi.opensite.config;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * JWT认证过滤器 - 负责验证和解析JWT令牌
 */
@Component
public class JwtAuthFilter extends OncePerRequestFilter {
    
    @Autowired
    private JwtAuthenticationFilter jwtUtil;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        // 如果是公开接口，直接放行
        if (isPublicEndpoint(request)) {
            filterChain.doFilter(request, response);
            return;
        }
        
        // 从请求头中提取token
        String token = extractTokenFromHeader(request);
        
        if (token != null) {
            try {
                // 使用JWT工具类解析token获取用户ID
                Claims claims = jwtUtil.parseToken(token);
                Long userId = claims.get("userId", Long.class);
                
                if (userId != null) {
                    // 创建认证对象
                    UsernamePasswordAuthenticationToken authentication = 
                        new UsernamePasswordAuthenticationToken(userId, null, 
                            Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
                    
                    // 设置认证上下文
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    
                    // 将userId设置到请求属性中，供控制器使用
                    request.setAttribute("userId", userId);
                }
            } catch (Exception e) {
                // token无效，清除认证上下文
                SecurityContextHolder.clearContext();
            }
        } else {
            // 没有token，清除认证上下文
            SecurityContextHolder.clearContext();
        }
        
        filterChain.doFilter(request, response);
    }
    
    /**
     * 判断是否为公开接口
     */
    private boolean isPublicEndpoint(HttpServletRequest request) {
        String requestPath = request.getRequestURI();
        
        // 注册和登录接口
        if ("/api/users/register".equals(requestPath) || "/api/users/login".equals(requestPath)) {
            return true;
        }
        
        // 精确匹配的公开接口
        if ("/api/activities/page".equals(requestPath) ||
            "/api/activities/upcoming".equals(requestPath) ||
            "/api/activities/hot".equals(requestPath) ||
            "/api/categories".equals(requestPath)) {
            return true;
        }
        
        // 匹配单个活动详情接口（/api/activities/{id}）
        if (requestPath.matches("/api/activities/\\d+")) {
            return true;
        }
        
        // 评论相关的公开接口
        if (requestPath.startsWith("/api/comments/activity/")) {
            return true;
        }
        
        return false;
    }
    
    /**
     * 从请求头提取token
     */
    private String extractTokenFromHeader(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}